package com.hotel.front;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.SharedCache;
import com.StatusTitle;
import com.Util;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.labs.repackaged.org.json.JSONException;
import com.google.gson.Gson;
import com.hotel.BL.AmenityLogic;
import com.hotel.BL.GenericLogic;
import com.hotel.BL.ReservationLogic;
import com.hotel.BL.RoomLogic;
import com.hotel.BL.RoomTypeLogic;

import data.Amenity;
import data.CleaningStatus;
import data.RoomType;
import data.passingData.ResultData;

@SuppressWarnings("serial")
public class RoomtypeService extends HttpServlet {
	//http://localhost:8080/roomtypeService?func=addRoomtype&shortName=shortname&imageCaption=111&StandardOccupancy=1&MaxOccupancy=1&extraBedAllowed=1&amenityListString=1&basePrice=1&higherPrice=1&extraBedPrice=1&applicableTaxListString=1&sortOrder=1
	//http://localhost:8080/roomtypeService?func=editRoomtype&roomtypeId=828&title=RoomtypeAB
	//http://localhost:8080/roomtypeService?func=delRoomtype&roomtypeId=828
	//http://localhost:8080/roomtypeService?func=changeRoomtype&roomtypeId=828
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		try{
			String doClass = req.getParameter("func");
			if(doClass.equals("addRoomtype")){
				AddRoomtype(req,resp);
			}else if(doClass.equals("editRoomtype")){
				EditRoomtype(req,resp);
			}else if(doClass.equals("delRoomtype")){
				DeleteRoomtype(req,resp);
			}else if(doClass.equals("changeRoomtype")){
				ChangeStatus(req,resp);
			}else if(doClass.equals("getAllRoomtype4Admin")){
				GetAllRoomtype4Admin(req,resp);
			}else if(doClass.equals("getRoomtypeById")){
				GetRoomtypeById(req,resp);
			}else if(doClass.equals("getAllRoomtype")){
				GetAllRoomType(req,resp);
			}else if(doClass.equals("editSortOrder")){
				EditSortOrder(req,resp);
			}else if(doClass.equals("getAmenityInRoom")){
				GetAmenityInRoomtype(req,resp);
			}else if(doClass.equals("getRoomtypeByIdCache")){
				GetRoomtypeByIdCache(req,resp);
			}else if(doClass.equals("addRoom")){
				AddRoom(req,resp);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void AddRoomtype(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException
	{	
		HttpSession session=req.getSession(true);
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		long hotelId = (Long) session.getAttribute("hotelId");
		String title = req.getParameter("title"); 
		String shortName = req.getParameter("shortName"); 
		String imageCaption = req.getParameter("imageCaption");
		long StandardOccupancy = Long.parseLong(req.getParameter("StandardOccupancy"));
		long MaxOccupancy = Long.parseLong(req.getParameter("MaxOccupancy"));
		long extraBedAllowed = Long.parseLong(req.getParameter("extraBedAllowed"));
		String amenityListString = req.getParameter("amenityListString");
		double basePrice = Double.parseDouble(req.getParameter("basePrice"));
		double extraBedPrice = Double.parseDouble(req.getParameter("extraBedPrice"));
		double upcharge = Double.parseDouble(req.getParameter("higherPrice"));
		String applicableTaxListString = req.getParameter("applicableTaxListString");
		long sortOrder = 0;
		String pic = req.getParameter("pic");
		String description = req.getParameter("description");
		
		Object obj = new RoomTypeLogic(req,resp).AddRoomtype(hotelId,title,shortName,
				imageCaption,StandardOccupancy,MaxOccupancy,
				extraBedAllowed,amenityListString,basePrice,
				extraBedPrice,applicableTaxListString,sortOrder,pic,description,upcharge);

		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(obj));
	}

	private void EditRoomtype(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException
	{	
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		long roomtypeId =0;
		if(!req.getParameter("id").equals("") || req.getParameter("id") != null ){
			roomtypeId	= Long.parseLong(req.getParameter("id"));
		}
		String title = req.getParameter("title");
		String shortName = req.getParameter("shortName"); 
		String imageCaption = req.getParameter("imageCaption");
		long StandardOccupancy = Long.parseLong(req.getParameter("StandardOccupancy"));
		long MaxOccupancy = Long.parseLong(req.getParameter("MaxOccupancy"));
		long extraBedAllowed = Long.parseLong(req.getParameter("extraBedAllowed"));
		String amenityListString = req.getParameter("amenityListString");
		double basePrice = Double.parseDouble(req.getParameter("basePrice"));
		double extraBedPrice = Double.parseDouble(req.getParameter("extraBedPrice"));
		double upcharge = Double.parseDouble(req.getParameter("higherPrice"));
		String applicableTaxListString = req.getParameter("applicableTaxListString");
		String pic = req.getParameter("pic");
		String description = req.getParameter("description");
		
		Object obj = new RoomTypeLogic(req,resp).EditRoomtype(roomtypeId,title,shortName,
				imageCaption,StandardOccupancy,MaxOccupancy,extraBedAllowed,
				amenityListString,basePrice,extraBedPrice,
				applicableTaxListString,pic,description,upcharge);
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(obj));

	}

	private void DeleteRoomtype(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException
	{	
		HttpSession session=req.getSession(true);
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		long hotelId = (Long) session.getAttribute("hotelId");
		String roomtypeIdList = req.getParameter("roomtypeId");
		long roomamount = 0;
		List<String> list = new ArrayList<String>();
		ReservationLogic resLogic = new ReservationLogic(req,resp);
		RoomTypeLogic roomTypeLogic = new RoomTypeLogic(req,resp);
		for(int i = 0; i < roomtypeIdList.split(",").length ; i++){
			long roomsize = resLogic.GetReservationByRoomType(hotelId, Long.parseLong(roomtypeIdList.split(",")[i])).size();
			roomamount += roomsize;
			if(roomsize !=0){
				list.add(roomTypeLogic.GetRoomType(Long.parseLong(roomtypeIdList.split(",")[i])).getShortName());
			}
		}
		if(roomamount == 0){
			for(int i=0;i<roomtypeIdList.split(",").length ; i++){
				roomTypeLogic.DeleteRoomtype(Long.parseLong(roomtypeIdList.split(",")[i]));
			}
			GetAllRoomtype4Admin(req, resp);
		}else{
			
			HashMap<String,Object> returndata = new HashMap<String,Object>();
			returndata.put("data",null);
			returndata.put("cantdelete",list);
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(returndata));
		}
	}

	private void ChangeStatus(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException
	{	
		HttpSession session=req.getSession(true);
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}	
		long hotelId = (Long) session.getAttribute("hotelId");
		long roomtypeId = Long.parseLong(req.getParameter("roomtypeId"));
		RoomTypeLogic roomTypeLogic = new RoomTypeLogic(req,resp);
		
		boolean isFoundUsed = roomTypeLogic.CanChangeRoomType(hotelId,roomtypeId);
		HashMap<String,Object> data = new HashMap<String,Object>();
		if(isFoundUsed){
			data.put("data", roomTypeLogic.GetRoomType(roomtypeId));
			data.put("canchange", false);
		}else{
			data.put("data", roomTypeLogic.ChangeStatus(roomtypeId));
			data.put("canchange", true);
		}
		
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(data));
	}
	
	private void GetAllRoomtype4Admin(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException
	{	
		HttpSession session=req.getSession(true);
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		long hotelId = (Long) session.getAttribute("hotelId");
		long offset = Long.parseLong(req.getParameter("offset"));
		long line = Long.parseLong(req.getParameter("line"));
		long pointer = Long.parseLong(req.getParameter("pagePointer"));
		RoomTypeLogic roomTypeLogic = new RoomTypeLogic(req,resp);
		RoomLogic roomLogic = new RoomLogic(req,resp);
		
		List<RoomType> obj = roomTypeLogic.GetAllRoomtype4AdminLimit(hotelId,offset,line);
		List<Object> roomamount = new ArrayList<Object>();
		for(int i =0;i<obj.size();i++){
			roomamount.add(i, roomLogic.GetRoom(hotelId,obj.get(i).getId()).size());
		}
		double dataSize = roomTypeLogic.GetAllRoomtype4Admin(hotelId).size();
		HashMap<String,Object> data = new HashMap<String,Object>();
		data.put("dataAmount",dataSize);
		data.put("pageNumber",pointer);
		data.put("lineAmount", line);
		data.put("pageAmount", Math.ceil(dataSize/line));
		data.put("data", obj);
		data.put("roomamount", roomamount);
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(data));
	}
	
	private void GetRoomtypeById(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException
	{	
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		long hotelId = 1;
		HttpSession session = req.getSession(true);
		if (session.getAttribute("hotelId") != null)
			hotelId = (Long) session.getAttribute("hotelId");
		Long id = Long.parseLong(req.getParameter("id"));
		RoomType obj = new RoomTypeLogic(req,resp).GetRoomType(id);
		int roomamount = new RoomLogic(req,resp).GetRoom(hotelId,obj.getId()).size();
		
		List<Amenity> amenityObj = new AmenityLogic().GetAllAmenity(hotelId);
		if(obj.getAmenityList() != null){
			for(int i=0;i<obj.getAmenityList().size();i++){
				for(int j=0;j<amenityObj.size();j++){
					if(obj.getAmenityList().get(i).getId() == amenityObj.get(j).getId()){
						amenityObj.remove(j);
						break;
					}
				}
			}			
		}
		List<Object> ansObj = Arrays.asList(obj,roomamount,amenityObj);
		resp.setContentType("text/plain; charset=UTF-8"); 
		resp.getWriter().println(gson.toJson(ansObj));
	}
	
	private void GetRoomtypeByIdCache(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException
	{
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		long hotelId = 1;
		HttpSession session = req.getSession(true);
		if (session.getAttribute("hotelId") != null)
			hotelId = (Long) session.getAttribute("hotelId");
		long id = Long.parseLong(req.getParameter("id"));
		RoomType obj;
		//For test cache
		if(SharedCache.getHotelCache(hotelId, "RoomtypeService.Roomtype")!=null)
			obj = (RoomType) SharedCache.getHotelCache(hotelId, "RoomtypeService.Roomtype");
		else{
			obj = new RoomTypeLogic(req,resp).GetRoomType(id);
			SharedCache.setHotelCache(hotelId, "RoomtypeService.Roomtype", obj, 5);
		}
		resp.setContentType("text/plain; charset=UTF-8"); 
		resp.getWriter().println(gson.toJson(obj));
	}
	
	private void GetAmenityInRoomtype(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException
	{
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		long id = Long.parseLong(req.getParameter("id"));
		RoomType obj = new RoomTypeLogic(req,resp).GetRoomType(id);
		Object ob = null;
		if(obj.getAmenityList() == null){
			ob = obj.getAmenityList();
		}
		resp.setContentType("text/plain; charset=UTF-8"); 
		resp.getWriter().println(gson.toJson(ob));
	}
	
	private void GetAllRoomType(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException
	{	
		HttpSession session = req.getSession(true);
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		long hotelId = 1;
		if (session.getAttribute("hotelId") != null)
			hotelId = (Long) (session.getAttribute("hotelId"));
		List<RoomType> obj = new RoomTypeLogic(req,resp).GetAllRoomType(hotelId);

		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(obj));
	}
	
	private void EditSortOrder(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException
	{
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		long roomtypeId = Long.parseLong(req.getParameter("id"));
		long sortOrder = Long.parseLong(req.getParameter("sortOrder"));
		
		RoomType a = new RoomTypeLogic(req,resp).EditSortOrder(roomtypeId,sortOrder);
		String x = "T";
		if(a == null){
			x = "F";
		}

		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(x));

	}
	
	private void AddRoom(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException
	{		
		HttpSession session=req.getSession(true);
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}	
		long hotelId = (Long) session.getAttribute("hotelId");
		
		String roomName = req.getParameter("roomname");
		String roomtypeString = req.getParameter("roomtype");
		String floorString = req.getParameter("floor");
		String blockString = req.getParameter("block");
		String comment = req.getParameter("description");
		CleaningStatus a = new GenericLogic(req,resp).GetCleaningStatus(hotelId,StatusTitle.CleaningStatusTitle.CleanRooms);
		String cleaningStatusString = String.valueOf(a.getId());

		new RoomLogic(req,resp).AddRoom(hotelId,roomName,roomtypeString,floorString,blockString,comment,cleaningStatusString,0);
		SharedCache.clearHotelCacheStartWith(hotelId,"RoomLogic");

		GetAllRoomtype4Admin(req, resp);
	}
}
